<?php

namespace App\Services\MakeVipPurchase;

use Carbon\Carbon;
use App\Models\User;
use App\Models\VipPurchase;
use Illuminate\Support\Facades\DB;
use App\Events\VipPurchasePaidEvent;

class MakeVipPurchase
{
	protected ?User $user = null;

	public function __construct($user, $method = null)
	{
		
		$this->user = $user instanceof User ? $user : User::find($user);
		$this->method = $method;
	}

	

	protected function getPendingPayingPurchase(User $user)
	{
		return $user->vipPurchases()
			->whereNull('closed_at')
			->whereNull('cancelled_at')
			->whereNull('paid_at')
			->whereNull('paid_method')
			->first();
	}
	
	public function buy()
	{
		/*if ($user->isVipBuyingLimited()) {
			throw ValidationException::withMessages(['err' => '流量达到峰值，请0点后再购买']);
		}*/

		if(empty($this->user->is_test) && empty($this->user->identify_num)){

				fail("用户未答题！");
		}

		 if(empty($this->user->identify_num)){

		 	fail("用户未实名认证！");
		 }
		
		$purchase = $this->getPendingPayingPurchase($this->user);
		
		
		$vipPrice = cs('sale')->vip_price;
 
		if($this->method=="card"){
			$cards = $this->user->vip_cards;
			if($cards < 1){

				fail("用户vip卡不足！");
			}

			$purchase = $this->user->vipPurchases()->create([
				'total_amount' => $vipPrice,
				'paid_at' => Carbon::now(), 
				'paid_method' => 'card'
			]);

			account_cards($this->user)->minusUseVipCards(1);

			event(new VipPurchasePaidEvent($purchase));

		}else{

			$count = VipPurchase::query()->whereDate('paid_at',Carbon::now())->count();
			if($count > cs("sale")->one_day_vip_cards){

				fail("当前购卡已达上限");
			}
			if (!$purchase) {
				$purchase = $this->user->vipPurchases()->create([
					'total_amount' => $vipPrice,
				]);


			}
		
		}
		
		return $purchase;
	}
	
	public function make()
	{
		return $this->buy();
	}
}
